import Taro, { Component } from '@tarojs/taro';
import { View ,Input,Label,Text } from '@doctorwork/components';
import { Canvas , CoverView} from '@tarojs/components';
import { connect } from '@tarojs/redux';
import Navigate from '../../components/Navigate/index';
import { rewriteAddMTA } from '../../model/utils/rewrite';
import {track} from '../../utils/track';
import { rpxToPx } from '../../utils';
import './index.styl';

// let plugin = requirePlugin('routePlan');

@connect(({ report }) => ({
    ...report
}))
@rewriteAddMTA
export default class Station extends Component {
    constructor(props){
        super(props);

        this.state = {
        };
    }
    config = {
        navigationBarTitleText: '生成账单'
    };


    componentDidShow() {
        // this.drawCanvas();
        const {month} = this.$router.params || '2023-02';
        const carNumber = wx.getStorageSync('carNumber')||'京A00000';
        track('report_page_enter', {month, carNumber});
        this.initCanvasText();
        this.props.dispatch({
            type: 'report/init',
            payload: {
                month: month, 
                carNumber,
                callback: (reportData)=>{
                    reportData.month = month;
                    reportData.carNumber = carNumber;
                    this.drawCanvas(reportData);
                }
            }
        });
    }
    initCanvasText(){
        const _this = this;
        wx.createSelectorQuery()
            .select('#canvas')
            .fields({ node: true, size: true })
            .exec(res => {
                const canvas = res[0].node;
                _this.canvas = canvas;
                // Canvas 画布的实际绘制宽高
                const width = res[0].width;
                const height = res[0].height;

                // 初始化画布大小
                const dpr = wx.getWindowInfo().pixelRatio;
                canvas.width = width * dpr;
                canvas.height = height * dpr;
                // 渲染上下文
                const ctx = canvas.getContext('2d');
                ctx.scale(dpr, dpr);
                ctx.font = 'lighter 30px Georgia';
                ctx.fillStyle = '#00c365';
                ctx.fillText('账单生成中 ...', 100, 260, 200, 50);
                ctx.stroke();
            });
    }

    /**
     * 绘制月报
     */
    drawCanvas(reportData){
        const _this = this;
        console.log('账单生成中...');
        // wx.showLoading({
        //     title: '账单生成中...',
        // });
        wx.createSelectorQuery()
            .select('#canvas')
            .fields({ node: true, size: true })
            .exec(res => {
                const canvas = res[0].node;
                _this.canvas = canvas;
                // 渲染上下文
                const ctx = canvas.getContext('2d');
                const screenInfo = wx.getWindowInfo();
                // Canvas 画布的实际绘制宽高
                const width = res[0].width;
                const height = width / 750 * 1333;

                // 初始化画布大小
                const dpr = screenInfo.pixelRatio;
                canvas.width = width * dpr;
                canvas.height = height * dpr;
                ctx.scale(dpr, dpr);
                // 绘制背景图
                const bg = canvas.createImage();
                // bg.src = 'https://jingyikeji.fun/assets/report.png';
                bg.src = require('./report.png') ;
                bg.onload = ()=>{
                    ctx.clearRect(0,0,width, height);
                    ctx.drawImage(bg,0,0, width, height);
                    // 绘制车牌号
                    ctx.font = 'italic 30px Verdana';
                    ctx.fillStyle = '#000000';
                    ctx.fillText(reportData.carNumber, rpxToPx(100), rpxToPx(160));
                    // 绘制标题
                    ctx.font = '28px Georgia';
                    ctx.fillText(reportData.month, rpxToPx(150), rpxToPx(350));
                    // 绘制总金额
                    ctx.font = 'lighter 16px Georgia';
                    ctx.fillText('总金额:', rpxToPx(150), rpxToPx(510));
                    ctx.font = 'bolder 20px';
                    ctx.fillStyle = '#00c365';
                    ctx.fillText(reportData.totalPrice+' 元', rpxToPx(320), rpxToPx(510));
                    // 绘制行驶里程
                    ctx.fillStyle = '#000';
                    ctx.font = 'lighter 16px Georgia';
                    ctx.fillText('行驶里程:', rpxToPx(150), rpxToPx(570));
                    ctx.font = 'bolder 20px';
                    ctx.fillStyle = '#00c365';
                    ctx.fillText(reportData.totalMileage+' 公里',rpxToPx(320), rpxToPx(570));
                    // 绘制平均油耗
                    ctx.fillStyle = '#000';
                    ctx.font = 'lighter 16px Georgia';
                    ctx.fillText('平均油耗:', rpxToPx(150), rpxToPx(630));
                    ctx.font = 'bolder 20px';
                    ctx.fillStyle = '#00c365';
                    ctx.fillText(reportData.averageAmount+' 升/百公里',rpxToPx(320), rpxToPx(630));

                    // 绘制平均费率
                    ctx.fillStyle = '#000';
                    ctx.font = 'lighter 16px Georgia';
                    ctx.fillText('平均费率:', rpxToPx(150), rpxToPx(690));
                    ctx.font = 'bolder 20px';
                    ctx.fillStyle = '#00c365';
                    ctx.fillText(reportData.averagePrice+ ' 元/公里', rpxToPx(320), rpxToPx(690));


                    // 绘制提示文字
                    ctx.fillStyle = '#000';
                    ctx.font = 'lighter 12px Georgia';
                    ctx.fillText('提示: 每次月底加满油再记录、数据统计将更加准确哦', rpxToPx(100), rpxToPx(770));

                    ctx.stroke();
                    // wx.hideLoading();
                };

                
            });
    }

    /**
     * 下载canvans
     * @param {*} canvas 
     * @returns 
     */
    downloadCanvas(canvas){
        return new Promise((resolve, reject) => {
            wx.canvasToTempFilePath({
                canvas,
                success: res => {
                    // 生成的图片临时文件路径
                    const tempFilePath = res.tempFilePath;
                    resolve(tempFilePath);
                },
                fail : e => {
                    reject(e);
                }
            });
        });
    }

    /**
     * 保存网络图片到本地
     */
    async saveReport  () {
        // 埋点
        track('save_report_image');
        const canvas = this.canvas;
        const filePath = await this.downloadCanvas(canvas);
        return new Promise((resolve, reject) => {
            wx.saveImageToPhotosAlbum({
                filePath,
                success: function (res) {
                    wx.showToast({title: '保存成功',icon: 'success' });
                    resolve(res);
                },
                fail: (err) => {
                    if (
                        err.errMsg === 'saveImageToPhotosAlbum:fail auth deny' ||
                    err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied'
                    ) {
                        wx.showToast({title: '请打开"保存到相册"权限'});
                    } else {
                        wx.showToast({title:  '保存到手机相册出错, 请重试'});
                    }
                    reject(err);
                }
            });
        });
    };
    /**
     * 分享图片
     */
    async shareImg (){
        wx.showLoading({
            title: '生成中...',
            icon: 'none'
        });
        setTimeout(() => {
            wx.hideLoading();
        },1000);
        const tempFilePath =  await this.downloadCanvas(this.canvas);
        wx.showShareImageMenu({
            path: tempFilePath
        });
    }
    render() {
        return (
            <View className='container'>
                <Navigate
                    title='店老板二维码'
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                    showHomeBtn='true'
                />
                <Canvas className='report-canvas' id='canvas' type='2d' ></Canvas>
                <CoverView className='footer'>
                    <CoverView className='btn' onClick={this.shareImg.bind(this)} data-name='分享给好友'>分享给好友</CoverView>
                    <CoverView className='btn' onClick={this.saveReport.bind(this)} data-name='保存至相册'>保存至相册</CoverView>
                </CoverView>
                

            </View>

        );
    }
}
